<?php if(! defined('HAS_POWER') ) exit('无权访问!');
/**
==============================================================================
 * Class Route GracePHP的模块创建器
 * @author 肖永标
 * @date 2015-2-25
==============================================================================
 */

class GraceCreate {

    private $user;
    private $pass;

    public function __construct()
    {
        $this->user = Config::getItem('graceCreate.user');
        $this->pass = Config::getItem('graceCreate.password');
    }

    public function isLogin()
    {
        if(!$_COOKIE['adminCreate'])
            return false;

        return true;
    }

    public function login()
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST')
        {
            if($_POST['user'] == $this->user && $_POST['pass'] == $this->pass)
            {
                setcookie('adminCreate', $_POST['user']);
                $this->run();
            }
            else
            {
                $this->showError('账号或密码错误!');
            }
        }
        include SYSTEM . '/views/createLogin.php';
        exit;
    }

    public function run()
    {
        $var['apps'] = $this->_showApps();
        $var['tables'] = $this->_showTables();
        $var['models'] = $this->_showModels();
        $var['types'] = array('1'=>'控制器', '2'=>'模型');

        if($_SERVER['REQUEST_METHOD'] == 'POST')
        {
            if(isset($_GET['step']) && $_GET['step'] == 2)
            {
                $_SESSION['create']['currentApp'] = $_POST['app'];
            }
            elseif(isset($_GET['step']) && $_GET['step'] == 3)
            {
                $_SESSION['create']['currentType'] = $_POST['type'];
            }
            elseif(isset($_GET['step']) && $_GET['step'] == 'finish')
            {
                if($_SESSION['create']['currentType'] == 1)
                {
                    $controller = $_POST['controller'];
                    $model = $_POST['model'];

                    $content = file_get_contents(SYSTEM . '/ctemp/controller_temp.tpl');
                    $content = str_replace('%Model', ucfirst($controller), $content);
                    $content = str_replace('%model', $controller, $content);
                    $content = str_replace('%name', ucfirst($controller), $content);

                    $filename = Config::getItem('application') .
                        $_SESSION['create']['currentApp'] . '/controller/' . ucfirst($controller) . 'Controller.class.php';

                    if(!file_exists($filename))
                    {
                        $html = file_get_contents(SYSTEM . '/ctemp/html.tpl');
                        $viewDir = Config::getItem('application') . $_SESSION['create']['currentApp'] .'/views/' . strtolower($controller);
                        mkdir($viewDir);

                        $viewArr = array('index.php', 'insert.php', 'update.php');
                        foreach($viewArr as $k=>$v)
                        {
                            file_put_contents($viewDir . '/' . $v, $html);
                        }

                        file_put_contents($filename, $content);

                        $this->showSucc('控制器成功添加');
                    }
                    else
                    {
                        $this->showError('控制器已存在');
                    }
                }
                elseif($_SESSION['create']['currentType'] == 2)
                {
                    $table = $_POST['table'];
                    $content = file_get_contents(SYSTEM . '/ctemp/model_temp.tpl');
                    $content = str_replace('%Table', ucfirst($table), $content);
                    $content = str_replace('%table', $table, $content);

                    $filename = Config::getItem('application') .
                        $_SESSION['create']['currentApp'] . '/model/' . ucfirst($table) . 'Model.class.php';

                    if(!file_exists($filename))
                    {
                        file_put_contents($filename, $content);
                        $this->showSucc('模型成功添加');
                    }
                    else
                    {
                        $this->showError('模型已存在');
                    }
                }
            }
        }

        extract($var);

        include SYSTEM . '/views/createWeb.php';
        exit;
    }

    public function showError($msg)
    {
        $var['msg'] = $msg;
        extract($var);

        include SYSTEM . '/views/createErr.php';
        exit;
    }

    public function showSucc($msg)
    {
        $var['msg'] = $msg;
        extract($var);

        include SYSTEM . '/views/createSucc.php';
        exit;
    }

    private function _showApps()
    {
        $apps = array();
        $handle = opendir(Config::getItem('application'));

        while (false !== ($dir = readdir($handle))) {
            if($dir == '.' || $dir == '..')
                continue;
            $apps[] = $dir;
        }
        return $apps;
    }

    private function _showTables()
    {
        $host = Config::getItem('db.host');
        $user = Config::getItem('db.user');
        $pass = Config::getItem('db.pass');
        $name = Config::getItem('db.name');

        mysql_connect($host, $user, $pass);
        $tables = array();
        $query = mysql_query("show tables from $name");

        while(!!$row = mysql_fetch_row($query))
        {
            $tables[] = $row[0];
        }

        mysql_free_result($query);

        return $tables;
    }

    private function _showModels()
    {
        $app = $_SESSION['create']['currentApp'];

        $models = array();
        $handle = opendir(Config::getItem('application') . $app . '/model');

        while (false !== ($dir = readdir($handle))) {
            if($dir == '.' || $dir == '..')
                continue;
            $temp = explode('.', $dir);
            $models[] = $temp[0];
        }

        return $models;
    }
}